package com;
;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;

public class MyBatisSqlSessionFactory {
    public static SqlSessionFactory getMyBatisSqlSessionFactory(){
        SqlSessionFactory factory = null;
        try{
            InputStream inputStream = Resources.getResourceAsStream("config.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(inputStream);
            System.out.println("配置文件图纸："+ inputStream);
            System.out.println("创建工厂："+factory);
            return factory;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    //使用 Java API 配置 MyBatis
//    public static SqlSessionFactory getMyBatisSqlSessionFactory(){
//        SqlSessionFactory factory = null;
//        try{
//            //InputStream inputStream = Resources.getResourceAsStream("config.xml");
//            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//
//
//            //方法1：采用xml配置文件生成  【店长推荐】
//            //factory = builder.build(inputStream);
//
//            //方法2：采用java API的方式 【不推荐】
//            String driver = "com.mysql.cj.jdbc.Driver";
//            String url = "jdbc:mysql://localhost:3306/test01?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true";
//            String username = "root";
//            String password = "123456";
//            DataSource dataSource = new PooledDataSource(driver,url,username,password);
//            TransactionFactory transactionFactory = new JdbcTransactionFactory();
//            Environment environment = new Environment("mycom",transactionFactory,dataSource);
//            Configuration configuration = new Configuration(environment);
//            configuration.addMapper(TestDao.class);
//            factory = builder.build(configuration);
//            return factory;
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return null;
//    }
}
